<template>
  <div class="main_box">
    <el-row>
      <el-col :span="12">
        <div class="opration_wrap">
          <el-button
            type="primary"
            icon="fa fa-mail-forward"
            @click="returnList"
          >返回</el-button>
        </div>
      </el-col>
    </el-row>
    <div class="add_wrap">
      <div class="tit">
        <h2>基础信息</h2>
      </div>
      <el-form
        :model="goodsForm"
        ref="goodsForm"
        label-width="200px"
        :rules="roleRules"
      >
        <el-row>
          <el-form-item
            label="项目类型"
            prop="classOneId"
          >
            <el-select
              v-model="goodsForm.classOneId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingPro"
              placeholder="请输入项目类型"
              :filter-method="listClassOne"
              @change="handleClassOneChange"
            >
              <el-option
                v-for="item in classOneIdList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="医院名称"
            prop="institutionId"
          >
            <el-select
              v-model="goodsForm.institutionId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              placeholder="请输入医院名"
              :filter-method="listInstitution"
              @change="handleInstitutionChange"
            >
              <el-option
                v-for="item in pickInstitutionList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="产品名称"
            prop="goodsName"
          >
            <el-input
              v-model="goodsForm.goodsName"
              placeholder="商品前缀+属性+描述"
            >
              <template slot="prepend">{{this.goodsForm.projectName}}</template>
            </el-input>
          </el-form-item>
          <!--<el-form-item
            label="治疗医生"
            prop="doctorIds"
          >
            <el-select
              v-model="goodsForm.doctorIds"
              :disabled="false"
              filterable
              multiple
              clearable
              reserve-keyword
              placeholder="请输入医生姓名"
              :filter-method="listDoctor"
              :loading="loadingDoc"
              @change="handleDoctorChange"
              @focus="listDoctor"
            >
              <el-option
                v-for="item in pickDoctorList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>-->
          <!--<el-col>-->
            <el-form-item
              label="服务承诺"
              prop="servicePromise"
            >
              <!-- <el-radio-group v-model="goodsForm.servicePromise">
                <el-radio :label="1">无隐形消费</el-radio>
                <el-radio :label="2">未使用随时退</el-radio>
                <el-radio :label="3">需提前7天预约</el-radio>
              </el-radio-group> -->
              <el-select
                v-model="goodsForm.servicePromise"
                clearable
                placeholder="请选择服务承诺"
              >
                <el-option
                  v-for="item in servicePromiseOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>

            </el-form-item>
          <!--</el-col>-->
        </el-row>
        <div class="tit">
          <h2>上传产品图片</h2>
        </div>
        <el-row :gutter="20">
          <!-- <el-col :span="6">
            <div class="grid-content bg-purple">
               <el-form-item class="img_item" prop="goodsImageOneUrl">
                <div class="img">
                  <img :src="goodsForm.goodsImageOneUrl">
                  <i class="el-icon-plus" v-if="!goodsForm.goodsImageOneUrl"></i>
                </div>
                <div class="txt">
                  <span>商品图片一(封面)</span>
                </div>
                <el-input
                  type="file"
                  @change="handleFile('goodsImageOne','goodsImageOneUrl')"
                  id="goodsImageOne"
                  class="file"
                ></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
               <el-form-item class="img_item" prop="goodsImageTwoUrl">
                <div class="img">
                  <img :src="goodsForm.goodsImageTwoUrl">
                  <i class="el-icon-plus" v-if="!goodsForm.goodsImageTwoUrl"></i>
                </div>
                <div class="txt">
                  <span>商品图片二</span>
                </div>
                <el-input
                  type="file"
                  @change="handleFile('goodsImageTwo','goodsImageTwoUrl')"
                  id="goodsImageTwo"
                  class="file"
                ></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
               <el-form-item class="img_item" prop="goodsImageThreeUrl">
                <div class="img">
                  <img :src="goodsForm.goodsImageThreeUrl">
                  <i class="el-icon-plus" v-if="!goodsForm.goodsImageThreeUrl"></i>
                </div>
                <div class="txt">
                  <span>商品图片三</span>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <el-form-item label="商品图片四" class="img_item" prop="goodsImageFourUrl">
                <div class="img">
                  <img :src="goodsForm.goodsImageFourUrl">
                  <i class="el-icon-plus" v-if="!goodsForm.goodsImageFourUrl"></i>
                </div>
                <div class="txt">
                  <span>商品图片四</span>
                </div>
              </el-form-item>
            </div>
          </el-col> -->

          <div>

            <el-upload
              :auto-upload="false"
              :action="uploadUrl"
              list-type="picture-card"
              ref="upload"
              drag
              :http-request="fnUploadRequest"
              :before-upload="fnBeforeUpload"
              :on-success="fnUploadSuccess"
              :on-exceed="fnUploadExceed"
              :on-change="fnUploadChange"
              :headers="uploadHeaders"
              :file-list="fileList"
              :limit="files"
              :disabled="disabled"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              multiple
            >
              <i class="el-icon-plus"></i>
              <!-- <i class="el-icon-upload"></i> -->
              <!-- <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div> -->
              <div
                slot="tip"
                class="el-upload-tip"
              >
                <ul style="margin-top: 50px;">
                  <li>1、至少上传一张,最多四张图片，第一张将会设为封面</li>
                  <li>2、图片文件大小不能超过1M</li>
                  <li>3、图片必须为正方形且图片尺寸必须大于或等于400×400（谨慎缩放，不然会导致图片模糊）</li>
                  <li>4、支持JPG,PNG格式</li>
                  <li>5、点击右上角的删除图片，单击换图</li>
                  <li>6、拖拽图片即可以实现图片的更换</li>
                  <li>7、请上传有版权且图像清晰的美女头像、仪器设备或针剂产品图片</li>
                </ul>
              </div>

            </el-upload>

            <el-dialog :visible.sync="dialogVisible">
              <img
                width="100%"
                :src="dialogImageUrl"
                alt=""
              >
            </el-dialog>
            <el-button
              size="small"
              type="success"
              @click="submitUpload"
            >上传到服务器</el-button>
            <!-- 至少上传一张封面图片 -->
            <el-form-item
              label=""
              prop="goodsImageOneUrl"
            >
              <el-input
                type="hidden"
                v-model="goodsForm.goodsImageOneUrl"
              ></el-input>
            </el-form-item>

          </div>
        </el-row>

        <div class="tit">
          <h2>商品介绍</h2>
        </div>
        <el-row>
          <div style="width:100%;">
            <ul>
              <li>禁止留微信，电话，QQ等联系方式</li>
              <li>产品详情如含有价格应与提报价一致</li>
              <li>假体隆鼻或下巴隆胸等需放假体项目必须写明假体品牌</li>
              <li>手续类项目必须写明提报价有无包含麻醉费用或其他隐性消费</li>
              <li>不能含有"最"字，比如"最好"等字眼</li>
              <li>上传图片尺寸宽度为706px</li>
            </ul>
            <Editor
              class="editor"
              v-model="goodsForm.goodsDetails"
              :setting="editorSetting"
              @show="editors"
              :url="Url"
              :max-size="MaxSize"
              :accept="Accept"
              :with-credentials="withCredentials"
              @on-upload-fail="onEditorReady"
              @on-upload-success="onEditorUploadComplete"
            ></Editor>
          </div>
        </el-row>

        <div class="tit">
          <h2>完善产品价格</h2>
        </div>
        <el-row>

          <el-form-item
            label="商品最低价格"
            prop="retailPrice"
          >
            <el-input v-model="goodsForm.retailPrice"></el-input>
          </el-form-item>
          <el-form-item
            label="商品最高价格"
            prop="platformPrice"
          >
            <el-input v-model="goodsForm.platformPrice"></el-input>
          </el-form-item>
          <el-form-item
            label="商品数量"
            prop="surplusNum"
          >
            <el-input v-model="goodsForm.surplusNum"></el-input>
          </el-form-item>
          <el-form-item
            label="限购数量"
            prop="mostNum"
          >
            <el-input v-model="goodsForm.mostNum"></el-input>
          </el-form-item>

          <!--<el-form-item
            label="是否支持花花卡"
            prop="isFlower"
          >
            <el-radio-group v-model="goodsForm.isFlower">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="是否套餐商品"
            prop="isMeal"
          >
            <el-radio-group v-model="goodsForm.isMeal">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>-->

        </el-row>

        <!--<div class="tit">
          <h2>商品其他信息</h2>
        </div>
        <div style="margin-top:15px">
          &lt;!&ndash; <fieldset>
          <legend style="font-size:16px">商品其他信息</legend> &ndash;&gt;
          <el-form-item
            label="服务承诺时间"
            prop="serviceTimeType"
          >
            <el-col :span="11">
              &lt;!&ndash; <el-radio-group v-model="goodsForm.serviceTimeType">
              <el-radio :label="1">一个月</el-radio>
              <el-radio :label="2">两个月</el-radio>
              <el-radio :label="3">三个月</el-radio>
              <el-radio :label="4">自定义</el-radio>
            </el-radio-group> &ndash;&gt;
              <el-select
                v-model="goodsForm.serviceTimeType"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in serviceTimeTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="11">

              &lt;!&ndash; <el-input-number :min="4"
              v-model="goodsForm.serviceTimeRemark"
             ></el-input-number> &ndash;&gt;

              &lt;!&ndash; v-show="goodsForm.serviceTimeType == 4"              &ndash;&gt;
              <el-input-number
                v-show="goodsForm.serviceTimeType == 4"
                v-model="goodsForm.serviceTimeRemark"
                controls-position="right"
                :min="1"
                :max="999"
                :controls='false'
                placeholder="自定义"
              ></el-input-number>
            </el-col>
          </el-form-item>

          <el-form-item
            label="商品使用时间"
            prop="useTimeType"
          >
            <el-col :span="11">
              <el-radio-group v-model="goodsForm.useTimeType">
                <el-radio :label="1">医院正常营业时间均可</el-radio>
                <el-radio :label="2">自定义</el-radio>
              </el-radio-group>
            </el-col>
            <el-col :span="11">
              &lt;!&ndash; <p>组件值：{{ goodsForm.useTimeStEnd }}</p>
                form提交时赋值
                <p>组件值useTimeBegin：{{ goodsForm.useTimeBegin= goodsForm.useTimeStEnd[0] }}</p>
                <p>组件值useTimeEnd：{{ goodsForm.userTimeEnd = goodsForm.useTimeStEnd[1]}}</p> &ndash;&gt;

              &lt;!&ndash; v-show="goodsForm.useTimeType ==2" &ndash;&gt;
              <el-date-picker
                v-show="goodsForm.useTimeType ==2"
                v-model="goodsForm.useTimeStEnd"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-col>
          </el-form-item>
        </div>-->
        <!-- </fieldset> -->

        <div class="tit">
          <h2>添加商品规格</h2>
        </div>

        <el-row>



          <el-form :rules="model.rules" :model="model"  ref="form">

            <el-form-item
              label="选择规格（可多选）"
              prop="selectedSpecList"
              style="margin-bottom: 20px"
            >
              <el-select
                v-model="model.selectedSpecList"
                placeholder="选择规格"
                multiple
                @visible-change="getSpecList"
                @change="onSpecListChanged"
              >
                <el-option
                  v-for="item in model.specList"
                  :key="item.specId"
                  :label="item.specName"
                  :value="item.specId"
                >
                </el-option>
              </el-select>
              <p style="color: #ff0000;">*变动规格会导致数据清空，请先选好规格再填写</p>
              <p style="color: #ff0000;">*库存为必填数据，不填写将导致数据无法提交</p>
            </el-form-item>

            <!-- 表布局 -->


            <el-table
              border
              :data="model.tableData"
              v-if="model.selectedSpecList.length > 0"
              style="width: 100%;"
              max-height="320"
            >

              <el-table-column
                width="320px"
                v-for="(itemRow,index) in specs"
                :key="itemRow"
                :label="itemRow.rowName">
                <template slot-scope="scope">
                  <el-form-item :prop="'itemRow.rowValue'" style="margin-bottom: 20px;margin-top: 20px">

                    <!--<el-input style="width:80px"  v-model="" ></el-input>-->

                    <el-select
                      v-model="scope.row.specsValue[index]"
                      filterable
                      allow-create
                      default-first-option
                      placeholder="选择或输入具体规格">
                      <el-option
                        v-for="item in itemRow.specValueList"
                        :key="item.sid"
                        :label="item.sval"
                        :value="item.sval">
                      </el-option>
                    </el-select>

                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                width="140px"
                label="库存">
                <template slot-scope="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.stock'" style="margin-bottom: 28px;margin-top: 28px">
                    <el-input style="width:80px"  v-model="scope.row.stock" ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                width="140px"
                label="最低价格">
                <template slot-scope="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.minPrice'" style="margin-bottom: 28px;margin-top: 28px" >
                    <div style="height: 100%;display: flex; align-items: center; justify-content: center" >
                      <el-input style="width:80px"  v-model="scope.row.minPrice" ></el-input>
                    </div>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                width="140px"
                label="最高价格">
                <template slot-scope="scope">
                  <el-form-item :prop="'tableData.' + scope.$index + '.maxPrice'" style="margin-bottom: 28px;margin-top: 28px" >
                    <div style="height: 100%;display: flex; align-items: center; justify-content: center" >
                      <el-input style="width:80px"  v-model="scope.row.maxPrice" ></el-input>
                    </div>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                label="操作"
                fixed="right"
                min-width="200"
              >
                <template slot-scope="scope">
                  <el-button size="small" @click="deleteSpecs(scope.row)" >删除</el-button>
                  <el-button size="small" v-if="scope.$index == model.tableData.length-1" @click="addSpecs(scope.row)" >添加</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-row>

        <el-row>
          <el-form-item style="float:right">
            <el-button @click="returnList">关 闭</el-button>
            <el-button
              type="primary"
              @click="sureGoodsClick(1)"
            >保 存</el-button>
            <el-button
              type="primary"
              @click="sureGoodsClick(2)"
            >保存并送审</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>



  </div>
</template>

<script>
import * as validators from '@/utils/validators'
import * as message from '@/constants/message'
import Map from '@/components/MapComponent'
import Editor from '@/components/Editor' // 根据editor.vue组件位置引入
import { mapGetters, mapActions } from 'vuex'
export default {
  props: {},
  data () {
    return {
      servicePromiseOptions: [
        {
          value: '1',
          label: '无隐形消费'
        },
        {
          value: '2',
          label: '未使用随时退'
        },
        {
          value: '3',
          label: '需提前7天预约'
        }
      ],
      classOneIdList: [],
      /*projectProps: {
        label: 'className',
        value: 'classId'
      },*/
      //pickDoctorList: [],
      pickInstitutionList: [],
      loadingIns: false,
      //loadingDoc: false,
      loadingPro: false,
      serviceTimeTypeOptions: [
        {
          value: '30',
          label: '30天'
        },
        {
          value: '60',
          label: '60天'
        },
        {
          value: '90',
          label: '90天'
        },
        {
          value: '4',
          label: '自定义'
        }
      ],
      uploadUrl: '',
      uploadFileLength: 0,
      uploadFileSuccess: 0,
      uploadFileNames: [],
      uploadFileName: [],
      fileList: [],
      files: 4,
      disabled: false,
      uploadHeaders: {
        authorization: ''
      },
      dialogImageUrl: '',
      dialogVisible: false,
      goodsForm: {
        classOneId: '',
        classOneName: '',
        //classTwoId: '',
        //classTwoName: '',
        //projectId: '',
        //projectName: '',
        goodsName: '',
        institutionId: '',
        //doctorIds: '',
        servicePromise: '',
        goodsImageOneUrl: '',
        goodsImageTwoUrl: '',
        goodsImageThreeUrl: '',
        goodsImageFourUrl: '',
        //goodsType: '',
        retailPrice: '',
        platformPrice: '',
        //isFlower: 0,
        //isMeal: 0,
        surplusNum: '',
        mostNum: '',
        /*serviceTimeType: '',
        serviceTimeRemark: '',
        useTimeType: '',
        useTimeBegin: '',
        useTimeEnd: '',
        useTimeStEnd: '',*/
        goodsDetails: ''
      },
      editorSetting: {
        // 配置富文本编辑器高
        height: 200
      },
      Url: this.$Config.api.uploadOssApi, // 图片对应的上传地址
      MaxSize: 1048576, // 文件大小 1M
      Accept: 'image/jpeg, image/png', // 文件格式
      withCredentials: true,
      content: '', // 富文本编辑器双向绑定的内容
      roleRules: {
        classOneId: [
          {
            required: true,
            message: '请输入项目',
            trigger: 'blur'
          }
        ],
        goodsName: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }
        ],
        institutionId: [
          {
            required: true,
            message: '请输入医院',
            trigger: 'blur'
          }
        ],
        /*doctorIds: [
          {
            required: true,
            message: '请输入医生',
            trigger: 'blur'
          }
        ],*/
        servicePromise: [
          {
            required: true,
            message: '请输入服务承诺',
            trigger: 'blur'
          }
        ],
        goodsImageOneUrl: [
          {
            required: true,
            message: '请输入商品（封面）',
            trigger: 'blur'
          }
        ],
        surplusNum: [
          {
            required: true,
            message: '商品数量',
            trigger: 'blur'
          }
        ],
        /*mostNum: [
          {
            required: true,
            message: '限购数量',
            trigger: 'blur'
          }
        ],*/
        retailPrice: [
          {
            required: true,
            message: '请输入最低价格',
            trigger: 'blur'
          }
        ],
        platformPrice: [
          {
            required: true,
            message: '请输入最高价格',
            trigger: 'blur'
          }
        ],
        /*serviceTimeType: [
          {
            required: true,
            message: '服务承诺时间',
            trigger: 'blur'
          }
        ],
        useTimeType: [
          {
            required: true,
            message: '商品使用时间',
            trigger: 'blur'
          }
        ],*/
        goodsDetails: [
          {
            required: true,
            message: '商品详情',
            trigger: 'blur'
          }
        ]
      },
      form:{
        supplier2:"",
        type:"",
        desc:"",
        input:""
      },
      model:{
        specList:[],
        selectedSpecList:[],
        rules: {
          stock:{ type:"string",required:true,message:"必须填写库存",trigger:"blur"}
        },
        tableData:[{
          stock:"",
          maxPrice:"",
          minPrice:"",
          specsValue:[],
        }]
      },
      specs:[
      ],

    }
  },
  components: {
    Editor,
    Map
  },
  methods: {
    ...mapGetters({
      openTabs: 'getOpenTabs'
    }),
    ...mapActions({
      setOpenTabs: 'setOpenTabs',
      setActiveIndexPath: 'setActiveIndexPath',
      setDeleteTabs: 'setDeleteTabs',
      replaceOpenTab: 'replaceOpenTab'
    }),
    init () {
      let _this = this
      _this.listInstitution()
      _this.listClassOne()
    },
    // Editors
    editors (content) {
      // editor组件传过来的值赋给content
      console.log('editors>>>' + content)
      this.goodsForm.goodsDetails = content
    },
    onEditorReady (ins, ina) {
      // 上传失败的函数
      console.log('ins')
      console.log(ins)
      console.log(ina)
    },
    onEditorUploadComplete (json) {
      // 处理上传图片后返回数据，添加img标签到编辑框内
      console.log('json')
      console.log(json)
      console.log(json[0].location)
      this.content =
        this.content +
        '<img src=http://localhost:8008/' + json[0].location + '>'
    },
    sureGoodsClick (val) {
      let _this = this
      let msg = ''
      if (val === 1) {
        msg = message.MSG_CONFIRM_SAVE_ALTER
      } else if (val === 2) {
        msg = message.MSG_CONFIRM_SAVE_COMMIT_ALTER
      } else {
        return '操作类型有误！'
      }
      this.$refs.goodsForm.validate(valid => {
        if (valid) {
          _this.$confirm(msg, message.TITLE_PROMPT, {}).then(() => {
            _this.addGoods(val)
          })
        }
      })
    },
    addGoods (val) {
      let _this = this
      let productParam = [];
      for(let i = 0; i < this.model.tableData.length; i++){
        let specStr = this.model.tableData[i].specsValue.join(",");
        let specJsonStr = [];
        for (let j = 0; j < this.model.tableData[i].specsValue.length; j++) {
          specJsonStr.push({
            specType : 1,
            specName : this.specs[j].rowName,
            specId : this.specs[j].rowKey,
            specValue : this.model.tableData[i].specsValue[j]
          })
        }
        productParam.push(
          {
            platformPrice: this.model.tableData[i].maxPrice,
            retailPrice: this.model.tableData[i].minPrice,
            surplusNum: this.model.tableData[i].stock,
            specNames: specStr,
            specArray: JSON.stringify(specJsonStr)
          }
        )
      }
      let goodsFormData = {
        classOneId: _this.goodsForm.classOneId,
        classOneName: _this.goodsForm.classOneName,
        //classTwoId: _this.goodsForm.classTwoId,
        //classTwoName: _this.goodsForm.classTwoName,
        //projectId: _this.goodsForm.projectId,
        //projectName: _this.goodsForm.projectName,
        goodsName: _this.goodsForm.goodsName,
        institutionId: _this.goodsForm.institutionId,
        //doctorIds: _this.goodsForm.doctorIds == null ? '': _this.goodsForm.doctorIds.join(','),
        servicePromise: _this.goodsForm.servicePromise,
        goodsImageOneUrl: _this.goodsForm.goodsImageOneUrl.replace("blob:",""),
        goodsImageTwoUrl: _this.goodsForm.goodsImageTwoUrl,
        goodsImageThreeUrl: _this.goodsForm.goodsImageThreeUrl,
        goodsImageFourUrl: _this.goodsForm.goodsImageFourUrl,
        //isFlower: _this.goodsForm.isFlower,
        //isMeal: _this.goodsForm.isMeal,
        retailPrice: _this.goodsForm.retailPrice,
        platformPrice: _this.goodsForm.platformPrice,
        surplusNum: _this.goodsForm.surplusNum,
        mostNum: _this.goodsForm.mostNum < 1 ? 1 : _this.goodsForm.mostNum,
        serviceDays:
          _this.goodsForm.serviceTimeType === 4
            ? _this.goodsForm.serviceTimeRemark
            : _this.goodsForm.serviceTimeType,
        /*useTimeType: _this.goodsForm.useTimeType,
        useTimeBegin:
          _this.goodsForm.useTimeTyp === 3 ? _this.goodsForm.useTimeBegin : '',
        useTimeEnd:
          _this.goodsForm.useTimeTyp === 3 ? _this.goodsForm.useTimeEnd : '',*/
        goodsDetails: _this.goodsForm.goodsDetails,
        productAddParam : productParam
      }
      // TODO
      // val
      // 新增保存
      // 新增保存提交
      if (val === 1) {
        console.log('====保存===')
        goodsFormData.approveState = 2
      } else if (val === 2) {
        console.log('====保存并提交审核===')
        goodsFormData.approveState = 0
      }

      console.log('add>>>>' + JSON.stringify(goodsFormData))
      // TODO
      _this
        .$Post(_this.$Config.api.goods, goodsFormData)
        .then(data => {
          _this.$notify.success({
            title: message.TITLE_SUCCESS,
            message: message.MSG_ACTION_SUCCESS
          })
          _this.$router.push({ name: '商品列表' })
        })
        .catch(error => {
          if (error.msg) {
            _this.$notify.error({
              title: message.TITLE_ERROR,
              message: error.msg
            })
          }
        })
    },
    handleClassOneChange(val) {
      let obj = {};
      obj = this.classOneIdList.find((item)=>{
        return item.value === val;
      });
      this.goodsForm.classOneId = val;
      this.goodsForm.classOneName = obj.label;
    },
    addSpecs(row){
      this.model.tableData.push({
        stock:"",
        maxPrice:"",
        minPrice:"",
        specsValue:[]
    })
    },
    deleteSpecs(row){
      this.model.tableData.splice(row.$index,1)
    },
    /*handleProjectChange (value) {
      console.log('handleProjectChange>>>>' + value)
      let _this = this
      let cascaderProject = _this.$refs['cascaderProject']
      let projectValue = cascaderProject.currentValue
      let projectLables = _this.$refs['cascaderProject'].currentLabels
      console.log('handleProjectChange>>>>' + projectValue[0])
      console.log('handleProjectChange>>>>' + projectLables[0])
      _this.goodsForm.classOneId = projectValue[0]
      _this.goodsForm.classOneName = projectLables[0]

      _this.goodsForm.classTwoId = projectValue[1]
      _this.goodsForm.classTwoName = projectLables[1]

      _this.goodsForm.projectId = projectValue[2]
      _this.goodsForm.projectName = projectLables[2]
      console.log(
        'handleProjectChange>>>>' +
          _this.goodsForm.projectName +
          _this.goodsForm.projectId
      )
      console.log('projectId>>>>' + _this.goodsForm.classOneId)
      // _this.listDoctor()
    },
    listProject (query) {
      let _this = this
      _this.loadingPro = true
      _this
        .$Get(_this.$Config.api.projectTree)
        .then(res => {
          setTimeout(() => {
            _this.loadingPro = false
            // _this.pickProjectList = res.data
            _this.pickProjectList = res.data.map(item => {
              return {
                classId: item.classId,
                className: item.className,
                children: item.children
              }
            })
            // 处理子节点为空的情况 TODO:待优化
            _this.removeChildren(_this.pickProjectList)
            console.log('_this.pickProjectList>>>>>' + _this.pickProjectList)
          }, 200)
        })
        .catch(error => {
          _this.pickProjectList = []
          console.error(error)
        })
    },
    removeChildren (regions) {
      for (let i = 0, len = regions.length; i < len; i++) {
        if (regions[i].children.length === 0) {
          delete regions[i].children
        } else {
          this.removeChildren(regions[i].children)
        }
      }
    },*/
    handleInstitutionChange (value) {
      let _this = this
      console.log('institutionId>>>>' + value)
      // _this.listDoctor()
      this.goodsForm.doctorIds = [];

    },
    listInstitution (query) {
      let _this = this
      _this.loadingIns = true
      let cond = {
        pageNo: 1,
        pageSize: 500,
        institutionName: !query || typeof query !== 'string' ? '' : query,
        approveState: 1,
        state: 1
      }
      // console.log(cond)
      _this
        .$Get(_this.$Config.api.institus, cond)
        .then(res => {
          setTimeout(() => {
            _this.loadingIns = false
            _this.pickInstitutionList = res.data.list.map(item => {
              return {
                value: item.institutionId,
                label: item.institutionName
              }
            })
            console.log(
              '_this.pickInstitutionList>>>>>' + _this.pickInstitutionList
            )
          }, 200)
        })
        .catch(error => {
          _this.pickInstitutionList = []
          console.error(error)
        })
    },
    listClassOne (query) {
      let _this = this
      _this.loadingPro = true
      _this
        .$Get(_this.$Config.api.projectIds)
        .then(res => {
          setTimeout(() => {
            _this.loadingPro = false
            _this.classOneIdList = res.data.map(item => {
              return {
                value: item.classId,
                label: item.className
              }
            })
            console.log(
              '_this.classOneIdList>>>>>' + _this.classOneIdList
            )
          }, 200)
        })
        .catch(error => {
          _this.classOneIdList = []
          console.error(error)
        })
    },

    getSpecList (isShow) {
      if (isShow){
        console.log("tab----->    "+ JSON.stringify(this.model.tableData[0].specsValue))
        console.log("tab----->    "+ JSON.stringify(this.model.tableData))
        let _this = this;
        if (_this.goodsForm.institutionId){
          _this
            .$Get(_this.$Config.api.listByParam,{institutionId:_this.goodsForm.institutionId})
            .then(res => {
              _this.model.specList = res.data;
            })
            .catch(error => {
              _this.model.specList = []
              console.error(error)
            })
        }else{
          _this.$message.error('请先选择医院');
        }

      }
    },
    onSpecListChanged(){
      this.model.tableData = [{
        stock:"",
        maxPrice:"",
        minPrice:"",
        specsValue:[]
      }]
      this.specs = [];
      for(let i = 0; i < this.model.specList.length; i++){
         for(let j = 0; j < this.model.selectedSpecList.length; j++){
           console.log("ttt->" +JSON.stringify(this.model.specList[i]));
           if (this.model.selectedSpecList[j] == this.model.specList[i].specId) {
             this.specs.push({
               rowName: this.model.specList[i].specName,
               rowKey: this.model.specList[i].specId,
               rowValue: this.model.specList[i].specId,
               specValueList: this.model.specList[i].specValueList
             })
           }
         }
       }
      console.log("aaa---->  " + JSON.stringify(this.specs))
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleFile (id, data) {
      const $target = document.getElementById(id)
      const _this = this
      _this.disabled = true
      this.$Get(_this.$Config.api.uploadOssApi).then(res => {
        let OSS = require('ali-oss')
        let client = new OSS({
          region: _this.$Config.oss.region,
          accessKeyId: res.data.accessKeyId,
          accessKeySecret: res.data.accessKeySecret,
          stsToken: res.data.securityToken,
          bucket: _this.$Config.oss.bucket
        })
        const file = $target.files[0]
        const fileName = file.name
        const fileType = fileName.split("\.")[1];
        let fileTempName = new Date().getTime() + fileName.split("\.")[0];
        if (fileTempName.length > 5){
          fileTempName = fileTempName.substring(0,12);
        }
        const newName = fileTempName +"."+ fileType;
        const storeAs = 'web_images/Goods/' + newName;
        const resultUpload = ''
        client
          .put(storeAs, file, {})
          .then(function (r1) {
            let realUrl = r1.url.replace(_this.$Config.oss.ossUrl,_this.$Config.oss.realUrl);
            _this.goodsForm[data] = realUrl
          })
          .catch(function (err) {
            console.error(err)
          })
      })
    },
    async submitUpload (option) {
      // this.disabled = true
      this.$refs.upload.submit()
    },
    async fnUploadRequest (option) {

      console.log(option)
      try {
        let vm = this
        // vm.disabled = true
        // 获取OSS配置信息
        // TODO:OSS+el-upload

        // let ComponentApi = new ComponentApi()

        // let ret = await ComponentApi.fileOssParams()
        const _this = this
        // 已经上传过的不处理：情景先上传成功3个，后补充1个，之前3个会循环调用。
        if (option && option.response && option.response.url) {
          return
        }
        _this.$Get(_this.$Config.api.uploadOssApi).then(res => {
          let OSS = require('ali-oss')
          let client = new OSS({
            region: _this.$Config.oss.region,
            accessKeyId: res.data.accessKeyId,
            accessKeySecret: res.data.accessKeySecret,
            stsToken: res.data.securityToken,
            bucket: _this.$Config.oss.bucket
          })
          // const file = $target.files[0]
          let file = option.file
          if (!this.fnBeforeUpload(file)){
            return
          }
          // const file = this.$refs.upload.uploadFiles[0].raw
          const fileName = file.name
          const fileType = fileName.split("\.")[1];
          let fileTempName = new Date().getTime() + fileName.split("\.")[0];
          if (fileTempName.length > 5){
            fileTempName = fileTempName.substring(0,12);
          }
          const newName = fileTempName +"."+ fileType;
          const storeAs = 'web_images/Goods/' + newName;
          const resultUpload = ''
          console.log('fnUploadRequest>>>>>' + fileName)
          // TODO 测试 注释上传动作
          client
            .put(storeAs, file, {})
            .then(
              // response => {
              //   //debugger
              //   this.fnUploadSuccess(response, file, this.fileList)
              //   console.log('r1.url>>>>>>>>>' + response)
              //   //debugger
              // }

              function (ret) {
                if (ret.res.statusCode === 200) {
                  option.onSuccess(ret)
                  // 值回传
                  // //debugger
                  option.response = ret
                  let realUrl = r1.url.replace(_this.$Config.oss.ossUrl,_this.$Config.oss.realUrl);
                  console.log('r1.url>>>>>>>>>' + realUrl)
                  ret.url = realUrl;
                  return ret
                } else {
                  option.onError('上传失败')
                }
              // _this.goodsForm[data] = r1.url

              // 赋值
              // TODO:
                // file.url = r1.url
                // console.log('file.url>>>>>>>>>' + file.url)
              }
            )
            .catch(function (err) {
              console.error(err)
            })
        })

        // let ossData = JSON.parse(ret.data.data)
        // let relativePath = ossData.relativePath
        // let client = new OSS.Wrapper({
        //   policy: ossData.policy,
        //   accessKeyId: ossData.accessid,
        //   accessKeySecret: ossData.accesssecret,
        //   bucket: ossData.bucket,
        //   signature: ossData.signature
        // })
        // let file = option.file
        // const point = file.name.lastIndexOf('.')
        // let suffix = file.name.substr(point)
        // let fileName = file.name.substr(0, point)
        // let date = vm.$moment().format('YYYYMMDDHHmm')
        // let fileNames = `${fileName}_${date}${suffix}`
        // // 分片上传文件
        // // ret = await client.multipartUpload(relativePath + fileNames, file, {
        // //   progress: async function (p) {
        // //     let e = {}
        // //     e.percent = p * 100
        // //     option.onProgress(e)
        // //   }
        // // })
        // console.log(fileNames)

        // ret.res.statusCode = 200

        // if (ret.res.statusCode === 200) {
        //   option.onSuccess(ret)
        //   return ret
        // } else {
        //   vm.disabled = false
        //   option.onError('上传失败')
        // }
      } catch (error) {
        console.error(error)
        this.disabled = false
        option.onError('上传失败')
        this.$error(error.message)
      }
    },
    async fnUploadSuccess (response, file, fileLists) {
      console.log('file,>>>>' + JSON.stringify(file));
      let _this = this
      fileLists.forEach((item, index) => {
        //     _this.goodsForm.goodsImageOneUrl = item.
        if (item.response != undefined && item.response) {
          console.log(index + 'this fileList info:item name>>>>' + item.name + ' local url>>>>' + item.url + ' remote url>>' + item.response.url)
          if (index === 0) {
            _this.goodsForm.goodsImageOneUrl = item.response.url
          } else if (index === 1) {
            _this.goodsForm.goodsImageTwoUrl = item.response.url
          } else if (index === 2) {
            _this.goodsForm.goodsImageThreeUrl = item.response.url
          } else if (index === 3) {
            _this.goodsForm.goodsImageFourUrl = item.response.url
          }
          console.log('_this.goodsForm>>>>>>' + _this.goodsForm.goodsImageOneUrl)
          console.log('_this.goodsForm>>>>>>' + _this.goodsForm.goodsImageFourUrl)
        }
      })
    },
    fnUploadChange (file, fileList) {

    },
    /**
     * el-upload
     * on-exceed	文件超出个数限制时的钩子
     *  */
    fnUploadExceed (files, fileList) {
      let _this = this
      // _this.$message.warning(`当前限制选择 ${_this.files} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      _this.$message.warning(`当前限制最多 ${_this.files} 个文件!`)
    },
    fnBeforeUpload (file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isBMP = file.type === 'image/bmp';
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isJPG && !isPNG && !isBMP) {
        this.$message.error('上传图片只能是 JPG , PNG , BMP 格式!');
      }

      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return (isJPG || isPNG || isBMP) && isLt2M ;
    },
    returnList () {
      this.$router.push({path: '/good/goodManagement'});
    }
  },
  mounted () {
    this.init()
  }
}
</script>
<style lang="scss" src="@/assets/css/views/add.scss" scope>
el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 25px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.el-upload-dragger {
  width: 150px;
  height: 150px;
}
</style>
